<template>
  <div class="absent-register-container">
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef"
      label-width="100px" 
      class="register-form"
    >
      <el-form-item label="楼宇" prop="buildingId">
        <el-select 
          v-model="form.buildingId" 
          placeholder="请选择楼宇" 
          @change="handleBuildingChange"
        >
          <el-option 
            v-for="item in buildingList" 
            :key="item.id"
            :label="item.name" 
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="宿舍" prop="dormitoryId">
        <el-select 
          v-model="form.dormitoryId" 
          placeholder="请选择宿舍" 
          @change="handleDormitoryChange"
        >
          <el-option 
            v-for="item in dormitoryList" 
            :key="item.id"
            :label="item.name" 
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="学生" prop="studentId">
        <el-select 
          v-model="form.studentId" 
          placeholder="请选择学生"
        >
          <el-option 
            v-for="item in studentList" 
            :key="item.id"
            :label="item.name" 
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="原因" prop="reason">
        <el-input v-model="form.reason" />
      </el-form-item>

      <el-form-item label="日期" prop="createDate">
        <el-date-picker
          v-model="form.createDate"
          type="date"
          placeholder="选择日期"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">立即提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'  // 修改后的导入
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getBuildingList,
  getDormitoryByBuilding,
  getStudentByDormitory,
  saveAbsentRecord
} from '@/api/absent'

const router = useRouter()
const userStore = useUserStore()  // 使用Pinia store
const formRef = ref()

const form = ref({
  buildingId: '',
  dormitoryId: '',
  studentId: '',
  reason: '',
  createDate: '',
  dormitoryAdminId: ''
})

const buildingList = ref([])
const dormitoryList = ref([])
const studentList = ref([])

const rules = {
  buildingId: [{ required: true, message: '请选择楼宇', trigger: 'change' }],
  dormitoryId: [{ required: true, message: '请选择宿舍', trigger: 'change' }],
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  reason: [{ required: true, message: '请输入原因', trigger: 'blur' }],
  createDate: [{ required: true, message: '请选择日期', trigger: 'change' }]
}

// 获取楼宇列表
const fetchBuildingList = async () => {
  try {
    const res = await getBuildingList()
    buildingList.value = res.data
  } catch (error) {
    ElMessage.error('获取楼宇列表失败')
  }
}

// 楼宇选择变化
const handleBuildingChange = async () => {
  form.value.dormitoryId = ''
  form.value.studentId = ''
  if (!form.value.buildingId) return
  
  try {
    const res = await getDormitoryByBuilding(form.value.buildingId)
    dormitoryList.value = res.data
  } catch (error) {
    ElMessage.error('获取宿舍列表失败')
  }
}

// 宿舍选择变化
const handleDormitoryChange = async () => {
  form.value.studentId = ''
  if (!form.value.dormitoryId) return
  
  try {
    const res = await getStudentByDormitory(form.value.dormitoryId)
    studentList.value = res.data
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  }
}

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  
  try {
    await formEl.validate()
    form.value.dormitoryAdminId = userStore.admin.id  // 修改为使用Pinia
    
    const res = await saveAbsentRecord(form.value)
    if (res.code === 0) {
      await ElMessageBox.alert('缺寝登记成功', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/absentRecord2')
        }
      })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败:', error)
    }
  }
}

// 重置表单
const resetForm = (formEl) => {
  formEl?.resetFields()
}

// 初始化加载
onMounted(() => {
  fetchBuildingList()
})
</script>

<style scoped>
.absent-register-container {
  margin: 60px 0 0 330px;
  width: 400px;
}

.register-form {
  width: 100%;
}
</style>